﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.Craft;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.Craft
{
    public class UpdateCraftCommandHandler : IRequestHandler<UpdateCraftCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<CraftModel> _craft;
        private readonly IMapper _mapper;

        public UpdateCraftCommandHandler(IBaseRespository<CraftModel> craft, IMapper mapper)
        {
            _craft = craft;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateCraftCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>
            {
                Code = ApiEnum.Success,
                Msg = "更新工艺路线成功"
            };

            try
            {
                DateTime time = DateTime.Now;
                
                // 获取要更新的工艺路线
                var craftModel = await _craft.GetModelAsync(request.Id);
                if (craftModel == null)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "工艺路线不存在";
                    return result;
                }

                // 更新字段
               
                    craftModel.PreviewImage = request.PreviewImage;
                
                
                
                    craftModel.PriviewJson = request.PriviewJson;
                craftModel.CraftName = request.CraftName;
                craftModel.CraftDesc = request.CraftDesc;
                craftModel.CraftType = request.CraftType;
                craftModel.CraftStatus = request.CraftStatus;
                // 设置更新信息
                craftModel.UpdateName = request.UpdateName;
                craftModel.UpdateTime = time;

                // 执行更新
                result.Data = await _craft.Update(craftModel);
                
                if (result.Data <= 0)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "更新工艺路线失败";
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"更新工艺路线失败：{ex.Message}";
            }

            return result;
        }
    }
}
